package com.group7.mall.controller;

import com.group7.mall.bean.Result;
import com.group7.mall.dto.UserOrderDetailDto;
import com.group7.mall.dto.UserOrderDto;
import com.group7.mall.dto.UserOrderPreviewDto;
import com.group7.mall.entity.TbUserOrder;
import com.group7.mall.req.UserOrderPageRequest;
import com.group7.mall.resp.UserOrderPageResponse;
import com.group7.mall.service.UserOrderService;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("user-order")
public class CustomerOrderController {

    @Resource
    private UserOrderService userOrderService;

    @Resource
    private AmqpTemplate rabbitTemplate;

    private final ConcurrentHashMap<Integer, Instant> orderExpiryTimes = new ConcurrentHashMap<>();

    private final Duration ttl = Duration.ofSeconds(600);

    @PostMapping("show-order-detail")
    public Result<UserOrderDetailDto> showOrderDetail(@RequestBody UserOrderDto userOrderDto) {
        return Result.ok(userOrderService.showOrderDetail(userOrderDto));
    }

    @PostMapping("refund-before-shipment")
    public Result refundBeforeShipment (@RequestBody UserOrderDto userOrderDto) {
        int i = userOrderService.refundBeforeShipment(userOrderDto);
        Result result = Result.ok();
        if (i == -1) {
            result.setMessage("商家已发货！取消订单失败！");
        } else {
            result.setMessage("取消订单成功！");
        }
        result.setData(i);
        return result;
    }

    @PostMapping("user-apply-service")
    public Result userApplyService(@RequestBody UserOrderDto userOrderDto) {
        int i = userOrderService.userApplyService(userOrderDto);
        Result result = Result.ok();
        if (i == 1) {
            result.setMessage("用户申请售后成功！");
            result.setData(1);
            return result;
        } else {
            result.setMessage("用户申请售后失败！");
            result.setData(0);
            return result;
        }
    }


    @PostMapping("user-confirm-receipt")
    public Result userConfirmReceipt(@RequestBody TbUserOrder tbUserOrder) {
        int i = userOrderService.userConfirmReceipt(tbUserOrder);
        Result result = Result.ok();
        if (i == 1) {
            result.setMessage("用户确认收货成功！");
            result.setData(1);
            return result;
        } else {
            result.setMessage("用户确认收货失败！");
            result.setData(0);
            return result;
        }
    }

    @PostMapping("update-order-address")
    public Result updateOrderAddress(@RequestBody UserOrderDto userOrderDto) {
        int i = userOrderService.updateOrderAddress(userOrderDto);
        Result result = Result.ok();
        if (i == 1) {
            result.setMessage("修改订单收货地址成功！");
            result.setData(1);
            return result;
        } else {
            result.setMessage("修改订单收货地址失败！");
            result.setData(0);
            return result;
        }
    }

    @PostMapping("create-cart-order")
    public Result createCartUserOrder(@RequestBody UserOrderDto userOrderDto) {
        Result result = Result.ok();
        userOrderDto = userOrderService.createOrderByCart(userOrderDto);
        if (userOrderDto == null) {
            result.setMessage("创建订单失败！库存不足");
            result.setData(0);
        } else {
            result.setMessage("创建订单成功！");
            Instant enqueueTime = Instant.now(); // 当前时间作为入队时间
            Instant expiryTime = enqueueTime.plus(ttl); // 计算过期时间
            orderExpiryTimes.put(userOrderDto.getOrderId(), expiryTime);
            rabbitTemplate.convertAndSend("ex.order", "order", userOrderDto.getOrderId());
            result.setData(userOrderDto);
        }
        return result;
    }

    @PostMapping("create-goods-order")
    public Result createGoodsUserOrder(@RequestBody UserOrderDto userOrderDto) {
        Result result = Result.ok();
        userOrderDto = userOrderService.createOrderByGoods(userOrderDto);
        if (userOrderDto == null) {
            result.setMessage("创建订单失败！库存不足");
            result.setData(0);
        } else {
            result.setMessage("创建订单成功！");
            Instant enqueueTime = Instant.now(); // 当前时间作为入队时间
            Instant expiryTime = enqueueTime.plus(ttl); // 计算过期时间
            orderExpiryTimes.put(userOrderDto.getOrderId(), expiryTime);
            rabbitTemplate.convertAndSend("ex.order", "order", userOrderDto.getOrderId());
            result.setData(userOrderDto);
        }
        return result;
    }

    @PostMapping("query-order-remaining-time")
    public Result getOrderRemainingTime(@RequestBody UserOrderDto userOrderDto) {
        // 获取当前时间的Instant表示
        Instant currentTime = Instant.now();
        // 从ConcurrentHashMap中获取订单的过期时间
        Instant expiryTime = orderExpiryTimes.get(userOrderDto.getOrderId());
        Result result = Result.ok();
        if (expiryTime == null) {
            result.setMessage("订单不存在");
            return result;
        } else if (expiryTime.isBefore(currentTime) || expiryTime.equals(currentTime)) {
            // 订单已过期或正好到期
            result.setMessage("订单已过期");
            return result;
        } else {
            Duration remainingDuration = Duration.between(currentTime, expiryTime);
            long millis = remainingDuration.toMillis(); // 获取剩余毫秒数
            long seconds = millis / 1000; // 计算剩余秒数
            long minutes = seconds / 60; // 计算剩余分钟数
            seconds %= 60; // 秒数取模60，获取剩余的秒数部分
            millis %= 1000; // 毫秒数取模1000，获取剩余的毫秒数部分
            // 格式化剩余时间
            result.setMessage("订单未过期，请尽快支付");
            result.setData(String.format("%02d:%02d:%03d", minutes, seconds, millis));
            return result;
        }
    }

    @PostMapping("order-after-pay")
    public Result orderAfterPay(@RequestBody UserOrderDto userOrderDto) {
        int i = userOrderService.orderAfterPay(userOrderDto);
        Result result = Result.ok();
        if (i == -1) {
            result.setMessage("支付失败！商品种类不存在或商品已下架");
        } else if (i == 0) {
            result.setMessage("支付失败！商品数量大于库存数量");
        } else {
            result.setMessage("支付成功！");
        }
        result.setData(i);
        return result;
    }

    @PostMapping("show-user-order")
    public Result<UserOrderPageResponse<UserOrderPreviewDto>> showUserOrder(@RequestBody UserOrderPageRequest userOrderPageRequest) {
        return Result.ok(userOrderService.showUserOrder(userOrderPageRequest));
    }

    @PostMapping("cancel-unpaid-order")
    public Result cancelUnpaidOrder(@RequestBody UserOrderDto userOrderDto) {
        int i = userOrderService.cancelUnpaidOrder(userOrderDto);
        Result result = Result.ok();
        if (i == 1) {
            result.setMessage("取消订单成功！");
            result.setData(1);
            return result;
        } else {
            result.setMessage("取消订单失败！");
            result.setData(0);
            return result;
        }
    }
}
